/*
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "stdio.h"
#include "project.h"

#include "los_reg.h"
#include "los_interrupt.h"
#include "los_event.h"

#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif

extern EVENT_CB_S g_shellInputEvent;

UINT32 UartGetc()
{
    UINT32 c;

	c = Cy_SCB_UART_Get(UART0_HW);

	return (c == CY_SCB_UART_RX_NO_DATA) ? 0 : c;
}

INT32 UartPutc(INT32 c, VOID *file)
{
    return Cy_SCB_UART_Put(UART0_HW, c);
}

VOID ISR_UART0(VOID)
{
    /* Check for "RX fifo not empty interrupt" */
    if((UART0_HW->INTR_RX_MASKED & SCB_INTR_RX_MASKED_NOT_EMPTY_Msk ) != 0)
	{
        (void)LOS_EventWrite(&g_shellInputEvent, 0x1);

        /* Clear UART "RX fifo not empty interrupt" */
		UART0_HW->INTR_RX = UART0_HW->INTR_RX & SCB_INTR_RX_NOT_EMPTY_Msk;
	}

    return;
}

VOID Uart0Init()
{
    /* Start UART operation. */
    Cy_SCB_UART_Init(UART0_HW, &UART0_config, &UART0_context);
    Cy_SCB_UART_Enable(UART0_HW);
    return;
}

VOID Uart0RxIrqRegister()
{
    /* Unmasking only the RX fifo not empty interrupt bit */
    UART0_HW->INTR_RX_MASK = SCB_INTR_RX_MASK_NOT_EMPTY_Msk;

    /* Interrupt Settings for UART */
    //Cy_SysInt_Init(&UART0_SCB_IRQ_cfg, ISR_UART0);

     /* Enable the interrupt */
    //NVIC_EnableIRQ(UART0_SCB_IRQ_cfg.intrSrc);

	/* Use system vector table */
    (void)HalHwiCreate(UART0_SCB_IRQ_cfg.intrSrc,
                       UART0_SCB_IRQ_cfg.intrPriority,
					    0, (HWI_PROC_FUNC)ISR_UART0, 0);

    return;
}
#ifdef __cplusplus
#if __cplusplus
}
#endif /* __cplusplus */
#endif /* __cplusplus */
